package com.lvyq.myplayer.ui.activity

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.base.BaseActivity
import com.lvyq.myplayer.common.model.SexType
import com.lvyq.myplayer.common.model.SingerType
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.util.MockDataUtil
import com.lvyq.myplayer.service.AudioService
import com.lvyq.myplayer.ui.fragment.SingerListFragment

/**
 * 文件描述：SingerMainActivity
 * 作者：lvyq
 * 创建时间：2025-04-22
 * 修改时间：2025-04-22
 */
class SingerMainActivity : BaseActivity() {
    lateinit var singerLstView: ViewPager2
    lateinit var tabLayout: TabLayout
    lateinit var sexTypeTab: TabLayout
    lateinit var singerTypeTab: TabLayout
    val letters=MockDataUtil.letterVal()
    val sexTypeList = MockDataUtil.sexTypeList()
    val singerTypeList = MockDataUtil.singerTypeList()
    override var currentPlayAdapter: CurrentPlayLstAdapter? = null


    private var currentSingerType: SingerType? = null
    private var currentSexType: SexType? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_singer
    }

    override fun initData() {
        initPlayBoxService()
        singerLstView = findViewById(R.id.singerLst)
        tabLayout = findViewById(R.id.searchValTab)
        sexTypeTab = findViewById(R.id.sexTypeTab)
        singerTypeTab = findViewById(R.id.singerTypeTab)
        // 设置 ViewPager2 适配器
        singerLstView.adapter = object : FragmentStateAdapter(this) {

            //页数为字母的个数
            override fun getItemCount(): Int = letters.size

            override fun createFragment(position: Int): Fragment {
                val fragment = SingerListFragment()

                val args = Bundle().apply {
                    putString("LETTER", letters[position].toString())
                    putInt("SINGER_TYPE", currentSingerType?.value ?: -1) // 传递歌手类型
                    putInt("SEX_TYPE", currentSexType?.value ?: -1)       // 传递性别类型
                }
                fragment.arguments = args

                return fragment
            }


        }

        // 初始化歌手分类Tab
        initSingerTypeTab()

        // 初始化性别分类Tab
        initSexTypeTab()

        // 关联 letters 和 ViewPager2
        TabLayoutMediator(tabLayout, singerLstView) { tab, position ->
            tab.text = letters[position].toString()
        }.attach()

        // 默认选中第一个页面
        singerLstView.setCurrentItem(0, true)
    }
    private fun initPlayBoxService() {
        initMainPlayBoxListener()
        currentPlayAdapter=getAdapter()
        initAudioPlayLst(this)

        //设置viewpage2 适配器
        recreateViewPagerAdapter()
        initMainPlayStateChangeUI()
        // updateMainPlayStateBtn(false)
        var songInfo = MainAudioSharedPrefsManager.getSongInfo(this)
        var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this)
        //通过audioservice 播放,混合启动，保证退出当前页仍然播放
        val audioIntent = Intent(this, AudioService::class.java)
        //传递值到AudioService中
        audioIntent.putExtra("data",songInfo)
        audioIntent.putExtra("from",-1)
        audioIntent.putExtra("position",currentAudioPosition?.toInt())
        //绑定 BIND_AUTO_CREATE 服务未创建时创建并绑定
        bindService(audioIntent,connection, BIND_AUTO_CREATE)
        //启动
        startService(audioIntent)
    }
    private fun getAdapter(): CurrentPlayLstAdapter {
        return CurrentPlayLstAdapter(this)
    }


    private fun initSexTypeTab() {
        sexTypeList.forEach { type->
            val tab = sexTypeTab.newTab().apply {
                text=type.name
                tag=type
            }
            sexTypeTab.addTab(tab)
        }

        sexTypeTab.selectTab(sexTypeTab.getTabAt(0))
        sexTypeTab.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentSexType=sexTypeList[tab?.position?:0]
                updateAllFragments() // 更新所有页面
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

    }



    private fun initSingerTypeTab() {
        singerTypeList.forEach { type->
            val tab = singerTypeTab.newTab().apply {
                text = type.name
                tag = type
            }
            singerTypeTab.addTab(tab)
        }
        singerTypeTab.selectTab(singerTypeTab.getTabAt(0)) // 默认选中第一个
        singerTypeTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentSingerType = singerTypeList[tab?.position ?: 0]
                updateAllFragments() // 更新所有页面
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    private fun updateAllFragments() {
        val adapter = singerLstView.adapter as FragmentStateAdapter
        // 遍历所有页面并强制刷新（关键修改点）
        (0 until adapter.itemCount).forEach { position ->
            // 使用 findFragmentWithTag 获取真实存在的Fragment实例
            val fragment = supportFragmentManager.findFragmentByTag(
                "f${adapter.getItemId(position)}"
            ) as? SingerListFragment

            fragment?.updateFilters(
                currentSingerType?.value,
                currentSexType?.value
            )
        }
}

}